package com.beauty.order.service.impl;

import com.beauty.order.client.UserClient;
import com.beauty.order.result.Result;
import com.beauty.order.service.UserIntegrationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserIntegrationServiceImpl implements UserIntegrationService {

    private final UserClient userClient;
    
    @Override
    public Map<String, Object> getUserInfo(String userId) {
        log.info("【订单服务】开始获取用户[{}]基本信息", userId);
        try {
            Result<?> result;
            
            // 如果是客户ID格式，使用专门的API
            if (userId.startsWith("CUS")) {
                log.info("【订单服务】远程调用用户服务: GET /api/user/customer/{}", userId);
                result = userClient.getUserByCustomerId(userId);
            } else {
                log.info("【订单服务】远程调用用户服务: GET /api/user/{}", userId);
                result = userClient.getUserById(userId);
            }
            
            if (result.getCode() != 200) {
                log.error("【订单服务】获取用户信息失败: {}", result.getMessage());
                return new HashMap<>();
            }
            
            Map<String, Object> userInfo = (Map<String, Object>) result.getData();
            log.info("【订单服务】用户[{}]信息获取成功", userId);
            return userInfo;
        } catch (Exception e) {
            log.error("【订单服务】获取用户信息异常", e);
            return new HashMap<>();
        }
    }
    
    @Override
    public Map<String, Object> getUserProfile(String userId) {
        log.info("【订单服务】开始获取用户[{}]详细资料", userId);
        try {
            Result<?> result;
            
            // 如果是客户ID格式，先获取用户ID
            if (userId.startsWith("CUS")) {
                log.info("【订单服务】远程调用用户服务: GET /api/user/customer/{}", userId);
                Result<?> userResult = userClient.getUserByCustomerId(userId);
                if (userResult.getCode() != 200) {
                    log.error("【订单服务】获取用户信息失败: {}", userResult.getMessage());
                    return new HashMap<>();
                }
                Map<String, Object> userData = (Map<String, Object>) userResult.getData();
                userId = userData.get("id").toString();
            }
            
            log.info("【订单服务】远程调用用户服务: GET /api/user/profile/{}", userId);
            result = userClient.getUserProfile(userId);
            
            if (result.getCode() != 200) {
                log.error("【订单服务】获取用户资料失败: {}", result.getMessage());
                return new HashMap<>();
            }
            
            Map<String, Object> userProfile = (Map<String, Object>) result.getData();
            log.info("【订单服务】用户[{}]资料获取成功", userId);
            return userProfile;
        } catch (Exception e) {
            log.error("【订单服务】获取用户资料异常", e);
            return new HashMap<>();
        }
    }
} 